<!--
 * @Descripttion: 甘特图
 * @version: V1.0
 * @Author: GW
 * @Date: 2021-10-26 09:21:44
 * @LastEditors: GW
 * @LastEditTime: 2021-10-27 17:25:40
-->
<template>
    <div ref="gantt"></div>
</template>
 
<script>
import { gantt } from 'dhtmlx-gantt';
export default {
    name: 'gantt',
    props: {
        tasks: {
            type: Object,
            default () {
                return { data: [], links: [] }
            }
        },
    },

    mounted: function () {
        let that = this;

        gantt.locale = {
            date: {
                month_full: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                month_short: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
                day_full: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
                day_short: ["日", "一", "二", "三", "四", "五", "六"]
            },
            labels: {
                dhx_cal_today_button: "今天",
                day_tab: "日",
                week_tab: "周",
                month_tab: "月",
                new_event: "新建日程",
                icon_save: "保存",
                icon_cancel: "关闭",
                icon_details: "详细",
                icon_edit: "编辑",
                icon_delete: "删除",
                confirm_closing: "请确认是否撤销修改!", //Your changes will be lost, are your sure?
                confirm_deleting: "是否删除日程?",
                section_description: "描述",
                section_time: "时间范围",
                section_type: "类型",

                /* grid columns */

                column_text: "任务名",
                column_start_date: "开始时间",
                column_duration: "持续时间",
                column_add: "",

                /* link confirmation */

                link: "关联",
                confirm_link_deleting: "将被删除",
                link_start: " (开始)",
                link_end: " (完成)",

                type_task: "计划",//任务
                type_project: "项目",
                type_milestone: "里程碑",

                minutes: "分钟",
                hours: "小时",
                days: "天",
                weeks: "周",
                months: "月",
                years: "年"
            }
        };
        gantt.plugins({
            drag_timeline: true
        });


        //表头时间显示处理
        gantt.config.scale_height = 2 * 28;//2行，每行高28px
        gantt.config.scales = [
            // { unit: "year", step: 1, format: "%Y" },
            // { unit: "month", step: 1, format: "%Y年%M" },
            // { unit: "day", step: 1, format: "%d日" },

            { unit: "month", format: " %Y年%F" },
            { unit: "day", step: 1, format: "%j,星期%D" }

        ];
        // gantt.config.xml_date = "%Y%M%d";

        //当task的长度改变时，自动调整图表坐标轴区间用于适配task的长度
        gantt.config.fit_tasks = true;

        gantt.config.drag_resize = true;

        //双击task时，弹出lightbox弹出框
        gantt.config.details_on_dblclick = true;
        //左侧树型结构调整时，可以任意拖动任务到任意节点下
        gantt.config.order_branch = true;
        // gantt.config.order_branch_free = true;
        //在左侧任务列表的最后新增一个空白列，填写之后可以新增任务
        // gantt.config.placeholder_task = true;
        gantt.config.lightbox.sections = [
            { name: "description", height: 70, map_to: "text", type: "textarea", focus: true },
            { name: "type", height: 70, type: "typeselect", map_to: "type" },
            { name: "time", type: "duration", map_to: "auto" }
        ];
        gantt.attachEvent("onBeforeLightbox", function (id) {
            console.log(id)
            that.$emit('edit', [id]);
            //双击表格弹窗事件
            return false;
        });

        //图表刷新后，滚动条的位置跟原来保持一致
        gantt.config.preserve_scroll = true;
        // gantt.templates.rightside_text = function (start, end, task) {
        //     console.log(start, end, task);
        //     if (task.type == gantt.config.types.milestone) {
        //         return task.text;
        //     }
        //     return "";
        // };
        //图表拖拽
        gantt.attachEvent("onTaskDrag", function (id, mode, task, original) {
            console.log('图表拖拽:', id, mode, task, original)
            //any custom logic here
        });
        // 图表拖拽后触发
        gantt.attachEvent("onAfterTaskUpdate", function (id, item) {
            console.log('图表更新后:', id, item);
            that.$emit('save', { id, item });
            //any custom logic here
        });
        //在用户完成拖动并释放鼠标按钮后触发
        gantt.attachEvent("onAfterTaskDrag", function (id, mode, e) {
            console.log('完成拖动并释放鼠标按钮后触发:', id, mode, e)
            //any custom logic here
        });
        //在用户向甘特图添加任务后触发
        gantt.attachEvent("onAfterTaskAdd", function (id, item) {
            console.log('在用户向甘特图添加任务后触发:', id, item)
            //any custom logic here
        });
        gantt.attachEvent("onLinkClick", function (id, e) {
            console.log('当用户点击链接时触发:', id, e)
            //any custom logic here
        });
        gantt.attachEvent("onLinkIdChange", function (id, new_id) {

            console.log('当链接的 id 改变时触发:', id, e)

            //any custom logic here
        });
        //将新链接添加到甘特图后触发
        gantt.attachEvent("onAfterLinkAdd", function (id, item) {
            console.log('将新链接添加到甘特图后触发:', id, item, that.tasks)
            //any custom logic here
        });



        gantt.serverList("status", [
            { key: 0, label: "未完成" },
            { key: 1, label: "进行中" },
            { key: 2, label: "已完成" },
        ]);
        gantt.serverList("type", [
            { key: 1, label: "计划" },
            { key: 2, label: "里程碑" },
        ]);
        gantt.config.columns = [
            { name: "text", label: "名称", tree: true, width: 150 },//name 
            {
                name: "type_name", label: "类型", width: 80, align: "center", template: function (item) {
                    return that.byId(gantt.serverList('type'), item.type_name)
                }//类型: 1计划2:里程碑
            },
            {
                name: "progress", label: "进度", width: 80, align: "center", template: function (item) {
                    return parseInt((item.progress * 100)) + '%';
                },
            },//progressRate
            { name: "personLiableNames", label: "负责人", width: 80, align: "center", },
            { name: "start_date", label: "开始日期", width: 80, align: "center", template: function (item) {
                    return item.type_name == 2? '':item.start_date
                },},//beginDate
            { name: "end_date", label: "完成日期", width: 80, align: "center", },//endDate
            {
                name: "status", label: "状态", width: 80, align: "center", template: function (item) {
                    return that.byId(gantt.serverList('status'), item.status)
                },//状态 状态0未完成 1进行中 2已完成
            },
            // {
            //     name: "edit", label: "操作", width: 40, align: "center", template: function (item) {
            //         that.$emit('edit', item);
            //     },
            // },
            // { name: "add", width: 40 }
        ];
        // gantt.message({
        //     text: [
        //         "You can increase the height of any row of the gantt by resizing it in the grid.",
        //         "The height if an individual row can be set using the <b>row_height</b> and <b>bar_height</b> properties of the task object."
        //     ].join("<br><br>"),
        //     expire: -1
        // });
        // gantt.config.autoscroll = true;
        // gantt.config.resize_rows = true;

        var message = null;

        gantt.attachEvent("onBeforeRowResizeEnd", function (id, item, newHeight) {
            gantt.message.hide(message);
            message = null;
            gantt.message("<b>" + item.text + "</b> is now <b>" + newHeight + "px</b> height");
            return true;
        });
        gantt.attachEvent("onAfterRowResize", function (id, item, oldHeight, newHeight) {
            gantt.message.hide(message);
            message = null;
            gantt.message("<b>" + item.text + "</b> was <b>" + oldHeight + "px</b> height. <br><b>"
                + item.text + "</b> is now <b>" + newHeight + "px</b> height");
        });
        gantt.attachEvent("onColumnResize", function (index, column, new_width) {
            if (!message) {
                message = gantt.message({
                    expire: -1,
                    text: "<b>" + gantt.locale.labels["column_" + column.name]
                        + "</b> is now <b id='width_placeholder'></b><b>px</b> width"
                });
            }
            document.getElementById("width_placeholder").innerText = new_width
        });
        gantt.attachEvent("onRowResize", function (id, item, currentHeight) {
            if (!message) {
                message = gantt.message({
                    expire: -1,
                    text: "<b>" + item.text + "</b> is now <b id='height_placeholder'></b>" +
                        + "<b>px</b> height"
                });
            }
            document.getElementById("height_placeholder").innerText = currentHeight;
        });
        // function fixBarHeight (task) {
        //     task.bar_height = 30;
        //     return true;
        // }
        gantt.attachEvent("onTaskCreated", function (task) {
            task.projectId = 1;
            return true;
        });


        // gantt.attachEvent("onTaskLoading", fixBarHeight);
        // gantt.attachEvent("onTaskCreated", fixBarHeight);

        gantt.init(this.$refs.gantt);
        gantt.parse(this.tasks);
    },
    methods: {
        byId (list, id) {
            for (var i = 0; i < list.length; i++) {
                if (list[i].key == id)
                    return list[i].label || "";
            }
            return "";
        },
        ansyFun () {
            setTimeout(() => {
                console.log('this.tasks.data:', this.tasks.data)
                if (this.tasks.data.length > 0) {
                    this.tasks.data.forEach(item => {
                        if (item.type == 2) {
                            item.type = gantt.config.types.milestone;//里程碑
                        }
                        if (item.type == 1) {
                            item.type = gantt.config.types.projcet;//计划
                        }
                    });
                } else {
                    this.tasks.data = [];
                }

                gantt.init(this.$refs.gantt);
                gantt.parse(this.tasks);
            }, 300)
        }
    }
}
</script>
 
<style>
    @import '~dhtmlx-gantt/codebase/dhtmlxgantt.css';
    .gantt_row_project {
        font-weight: bold;
    }
    .gantt_grid_scale .gantt_grid_head_cell,
    .gantt_task .gantt_task_scale .gantt_scale_cell {
        font-weight: bold;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.7);
    }
</style>